package vashion.azeroth.core.service.impl.item;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vashion.azeroth.contant.ForestErrorEnum;
import vashion.azeroth.core.item.pojo.ForestDO;
import vashion.azeroth.core.manager.forest.BaseForestManager;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.item.ForestService;

import java.util.List;
import java.util.Map;

/**
 * Created by liuhe on 15/10/4.
 */
@Service
public class ForestServiceImpl implements ForestService {

    private final static Logger log = LoggerFactory.getLogger(ForestServiceImpl.class);


    @Autowired
    private BaseForestManager baseForestManager;

    public ApiResult<ForestDO> getForestDetail(long forestId, boolean useCache) {
        try {
            return ApiResult.newSuccessResult(baseForestManager.getWithCache(forestId));
        } catch (Exception e) {
            log.error("ForestServiceImpl.getForestDetail errror, forestId=" + forestId, e);
            return ApiResult.newErrorResult(ForestErrorEnum.SYSTEM_ERROR.getErrorCode(), ForestErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
    }

    public ApiResult<List<ForestDO>> getChildForestList(long forestId) {

        ApiResult<Map<ForestDO, List<ForestDO>>> forestTreeResult = this.getForestTree();
        if (!forestTreeResult.isSuccess()) {
            log.error("ForestServiceImpl.getChildForestList error, forest tree is empty");
            return ApiResult.newErrorResult(ForestErrorEnum.SYSTEM_ERROR.getErrorCode(), ForestErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
        for (Map.Entry<ForestDO, List<ForestDO>> entry : forestTreeResult.getData().entrySet()) {
            if (entry.getKey().getId() == forestId) {
                return ApiResult.newSuccessResult(entry.getValue());
            }
        }
        return ApiResult.newErrorResult(ForestErrorEnum.IS_NULL.getErrorCode(), ForestErrorEnum.IS_NULL.getErrorMessage());
    }

    public ApiResult<Map<ForestDO, List<ForestDO>>> getForestTree() {
        try {
            return baseForestManager.getForestTree();
        } catch (Exception e) {
            log.error("ForestServiceImpl.getForestDetail getForestTree", e);
            return ApiResult.newErrorResult(ForestErrorEnum.SYSTEM_ERROR.getErrorCode(), ForestErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
    }
}
